<?php

namespace app\admin\controller\xiluhouse\rent;

use app\common\controller\Backend;
use app\common\model\xiluhouse\VillageBroker;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use function fast\array_get;

/**
 * 小区管理
 *
 * @icon fa fa-circle-o
 */
class Village extends Backend
{

    /**
     * Village模型对象
     * @var \app\common\model\xiluhouse\Village
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\xiluhouse\Village;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("checkStatusList", $this->model->getCheckStatusList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }

                    $data = $this->request->post("");
                    //拼接地址
                    $params['prov'] = $data['prov'];
                    $params['city'] = $data['city'];
                    $params['region'] = $data['region'];
                    $params['street'] = $data['street'];
                    if (!$params['lat'] || !$params['lng']) {
                        $address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $params['addr'];
                        $result = getGeo($address);
                        if ($result['status'] == 0) {
                            exception('获取经纬度失败，请选择正确的地址');
                        }
                        $params['lat'] = $result['lat'];
                        $params['lng'] = $result['lng'];
                    }
                    #地铁数据
                    $subway_distance = floatval(\app\common\model\xiluhouse\Config::getdatas('subway_distance')) / 1000;
                    $field_text = 'ACOS(SIN((' . $params['lat'] . '*3.1415)/180)*SIN((lat*3.1415)/180)+COS((' . $params['lat'] . '*3.1415)/180)*COS((lat*3.1415)/180)*COS((' . $params['lng'] . '*3.1415)/180-(lng*3.1415)/180))*6380 as distance';
                    $nearbySubwayData = \app\common\model\xiluhouse\SubwayPlatform::field('*,' . $field_text)->order('distance asc')->find();
                    // 处理地铁距离
                    if ($nearbySubwayData && $nearbySubwayData['distance'] <= $subway_distance) {
                        $params['subway_platform_id'] = $nearbySubwayData['id'];
                        //改成地铁线id
                        $ids_arr = \app\common\model\xiluhouse\Subway::where('code', 'in', $nearbySubwayData['subways'])->column('id');
                        $params['subway_ids'] = implode(',', $ids_arr);
                        $params['subway_distance'] = $nearbySubwayData['distance'] * 1000;
                        $params['subway_distance_text'] = '距离地铁' . $nearbySubwayData['name'] . intval($params['subway_distance']) . 'm';
                    }

                    // 处理周边地址
                    $params['nearby_bus_num'] = 0;
                    if ($params['nearby_bus_json']) {
                        $arr = json_decode($params['nearby_bus_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_bus_num'] = count($arr);
                        $params['nearby_bus_json'] = json_encode($arr);
                    }
                    $params['nearby_subway_num'] = 0;
                    if ($params['nearby_subway_json']) {
                        $arr = json_decode($params['nearby_subway_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_subway_num'] = count($arr);
                        $params['nearby_subway_json'] = json_encode($arr);
                    }
                    $params['nearby_school_num'] = 0;
                    if ($params['nearby_school_json']) {
                        $arr = json_decode($params['nearby_school_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_school_num'] = count($arr);
                        $params['nearby_school_json'] = json_encode($arr);
                    }
                    $params['nearby_shop_num'] = 0;
                    if ($params['nearby_shop_json']) {
                        $arr = json_decode($params['nearby_shop_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_shop_num'] = count($arr);
                        $params['nearby_shop_json'] = json_encode($arr);
                    }
                    $params['nearby_hospital_num'] = 0;
                    if ($params['nearby_hospital_json']) {
                        $arr = json_decode($params['nearby_hospital_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_hospital_num'] = count($arr);
                        $params['nearby_hospital_json'] = json_encode($arr);
                    }

                    $result = $this->model->allowField(true)->save($params);
                    $result2 = VillageBroker::setBrokerIds($this->model,array_get($params,'broker_user_ids'));
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }

                    $data = $this->request->post("");
                    //拼接地址
                    $params['prov'] = $data['prov'];
                    $params['city'] = $data['city'];
                    $params['region'] = $data['region'];
                    $params['street'] = $data['street'];
                    if (!$params['lat'] || !$params['lng']) {
                        $address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $params['addr'];
                        $result = getGeo($address);
                        if ($result['status'] == 0) {
                            exception('获取经纬度失败，请选择正确的地址');
                        }
                        $params['lat'] = $result['lat'];
                        $params['lng'] = $result['lng'];
                    }

                    $subway_distance = floatval(\app\common\model\xiluhouse\Config::getdatas('subway_distance')) / 1000;
                    $field_text = 'ACOS(SIN((' . $params['lat'] . '*3.1415)/180)*SIN((lat*3.1415)/180)+COS((' . $params['lat'] . '*3.1415)/180)*COS((lat*3.1415)/180)*COS((' . $params['lng'] . '*3.1415)/180-(lng*3.1415)/180))*6380 as distance';
                    $nearbySubwayData = \app\common\model\xiluhouse\SubwayPlatform::field('*,' . $field_text)->order('distance asc')->find();
                    // 处理地铁距离
                    if ($nearbySubwayData && $nearbySubwayData['distance'] <= $subway_distance) {
                        $params['subway_platform_id'] = $nearbySubwayData['id'];
                        //改成地铁线id
                        $ids_arr = \app\common\model\xiluhouse\Subway::where('code', 'in', $nearbySubwayData['subways'])->column('id');
                        $params['subway_ids'] = implode(',', $ids_arr);
                        $params['subway_distance'] = $nearbySubwayData['distance'] * 1000;
                        $params['subway_distance_text'] = '距离地铁' . $nearbySubwayData['name'] . intval($params['subway_distance']) . 'm';
                    }
                    // 处理周边地址
                    $params['nearby_bus_num'] = 0;
                    if ($params['nearby_bus_json']) {
                        $arr = json_decode($params['nearby_bus_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_bus_num'] = count($arr);
                        $params['nearby_bus_json'] = json_encode($arr);
                    }
                    $params['nearby_subway_num'] = 0;
                    if ($params['nearby_subway_json']) {
                        $arr = json_decode($params['nearby_subway_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_subway_num'] = count($arr);
                        $params['nearby_subway_json'] = json_encode($arr);
                    }
                    $params['nearby_school_num'] = 0;
                    if ($params['nearby_school_json']) {
                        $arr = json_decode($params['nearby_school_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_school_num'] = count($arr);
                        $params['nearby_school_json'] = json_encode($arr);
                    }
                    $params['nearby_shop_num'] = 0;
                    if ($params['nearby_shop_json']) {
                        $arr = json_decode($params['nearby_shop_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_shop_num'] = count($arr);
                        $params['nearby_shop_json'] = json_encode($arr);
                    }
                    $params['nearby_hospital_num'] = 0;
                    if ($params['nearby_hospital_json']) {
                        $arr = json_decode($params['nearby_hospital_json'], true);
                        foreach ($arr as $key => $value) {
                            if ($value['lat']) {
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $value['lat'], $value['lng']) . 'm';
                            } else {
                                $now_address = $params['prov'] . $params['city'] . $params['region'] . $params['street'] . $value['name'];
                                $addr_res = getGeo($now_address);
                                if ($addr_res['status'] == 0) {
                                    exception('获取经纬度失败，请选择正确的地址');
                                }
                                $arr[$key]['lat'] = $addr_res['lat'];
                                $arr[$key]['lng'] = $addr_res['lng'];
                                $arr[$key]['distance'] = '距离' . getDistanceWithTencent($params['lat'], $params['lng'], $arr[$key]['lat'], $arr[$key]['lng']) . 'm';
                            }
                        }
                        $params['nearby_hospital_num'] = count($arr);
                        $params['nearby_hospital_json'] = json_encode($arr);
                    }
                    $result = $row->allowField(true)->save($params);
                    $result2 = VillageBroker::setBrokerIds($row,array_get($params,'broker_user_ids'),'edit');
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $broker_user_ids = VillageBroker::where('village_id',$row->id)->column('broker_user_id');

        $this->view->assign('broker_user_ids',implode(',',$broker_user_ids));
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
}
